package com.student.dms;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.luck.picture.lib.utils.ToastUtils;
import com.student.db.AccountDao;
import com.student.db.AccountEntity;
import com.student.db.AppDatabase;
import com.student.dms.databinding.ActivityChangeInfoBinding;
import com.student.dms.databinding.ActivityChangePasswordBinding;

import java.io.ByteArrayOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class ChangeInfoActivity extends BaseActivity{

    private ActivityChangeInfoBinding activityChangeInfoBinding;
    private AppDatabase roomDatabase;
    private AccountDao accountDao;
    private AccountEntity accountEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityChangeInfoBinding = ActivityChangeInfoBinding.inflate(getLayoutInflater());
        setContentView(activityChangeInfoBinding.getRoot());
        SharedPreferences sharedPreferences =getSharedPreferences("user", Context.MODE_PRIVATE);
        String username = sharedPreferences.getString("username", "");
        roomDatabase = DMSApplication.getApplication().getRoomDatabase();
        accountDao = roomDatabase.provideAccountDao();
        Single<AccountEntity> accountFlow = accountDao.searchAccountByName(username);
        activityChangeInfoBinding.titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(TitleBar titleBar) {
                finish();
            }

            @Override
            public void onRightClick(TitleBar titleBar) {
                if(accountEntity.getType()!=1){
                    disposable.add(accountDao.deleteAccount(accountEntity).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(()->{
                        ChangeInfoActivity.this.finish();
                    }));

                }
            }
        });
     //   SharedPreferences.Editor edit = sharedPreferences.edit();
       // activityChangeInfoBinding.username.setText(username);

        Intent intent = getIntent();
        this.accountEntity = intent.getParcelableExtra("userInfo");
        if(this.accountEntity==null){
            disposable.add(accountFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(accountEntity -> {
                this.accountEntity=accountEntity;
                int sex = accountEntity.getSex();
                if(sex==1){
                    activityChangeInfoBinding.rgSelectSex.check(R.id.male);
                }else{
                    activityChangeInfoBinding.rgSelectSex.check(R.id.female);
                }
                activityChangeInfoBinding.username.setText(accountEntity.getUserName());
                activityChangeInfoBinding.roomNo.setText(accountEntity.getRoomNo());
                activityChangeInfoBinding.floorNo.setText(accountEntity.getFloorNo());
                activityChangeInfoBinding.editName.setText(accountEntity.getName());
                activityChangeInfoBinding.editPhoneNumber.setText(accountEntity.getPhoneNum());
                //RadioButton selectedRadioButton1 = findViewById(activityChangeInfoBinding.rgSelectSex.getCheckedRadioButtonId());
            }, studentFlowThrowable -> {
                ToastUtils.showToast(ChangeInfoActivity.this, "用户不存在，请注册！");
            }));
        }else{
            int sex = accountEntity.getSex();
            if(sex==1){
                activityChangeInfoBinding.rgSelectSex.check(R.id.male);
            }else{
                activityChangeInfoBinding.rgSelectSex.check(R.id.female);
            }
            activityChangeInfoBinding.username.setText(accountEntity.getUserName());
            activityChangeInfoBinding.roomNo.setText(accountEntity.getRoomNo());
            activityChangeInfoBinding.floorNo.setText(accountEntity.getFloorNo());
            activityChangeInfoBinding.editName.setText(accountEntity.getName());
            activityChangeInfoBinding.editPhoneNumber.setText(accountEntity.getPhoneNum());
            if(this.accountEntity.getType()!=1){
                activityChangeInfoBinding.titleBar.setRightTitle("删除");
            }
        }

        activityChangeInfoBinding.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String editName = activityChangeInfoBinding.editName.getText().toString().trim();
                String editPhoneNumber = activityChangeInfoBinding.editPhoneNumber.getText().toString().trim();
                if(checkInputIsNull(editName)||checkInputIsNull(editPhoneNumber)||checkInputIsNull(activityChangeInfoBinding.rgSelectSex)){
                    ToastUtils.showToast(ChangeInfoActivity.this, "性别选择和输入不能为空！");
                    return;
                }
                accountEntity.setName(editName);
                accountEntity.setPhoneNum(editPhoneNumber);
                RadioButton selectedRadioButton = findViewById(activityChangeInfoBinding.rgSelectSex.getCheckedRadioButtonId());
                int sex;
                if (selectedRadioButton.getText().equals("男")) {
                    sex = 1;
                } else {
                    sex = 0;
                }
                accountEntity.setSex(sex);
                disposable.add(accountDao.insert(accountEntity).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(()->{
                    ToastUtils.showToast(ChangeInfoActivity.this, "个人信息修改成功！");
                    ChangeInfoActivity.this.finish();
                }));
            }
        });

    }
    private boolean checkInputIsNull(RadioGroup radioGroup) {
        return radioGroup.getCheckedRadioButtonId() == -1;
    }
    private boolean checkInputIsNull(String editText) {
        return TextUtils.isEmpty(editText);
    }



    public boolean checkPassword(String password) {
        // 定义正则表达式，用于验证密码格式
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[\\W_]).{8,12}$";
        // 编译正则表达式为模式对象
        Pattern pattern = Pattern.compile(regex);
        // 创建匹配器对象，用于匹配输入的密码字符串
        Matcher matcher = pattern.matcher(password);
        // 通过匹配器的matches方法判断是否匹配成功，返回结果
        return matcher.matches();
    }

}
